package com.njrsrc.android.tasks;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.njrsrc.android.bean.Company;
import com.njrsrc.android.bean.JobInfo;
import com.njrsrc.android.bean.UserInfo;
import com.njrsrc.common.utils.Helpers;
import com.njrsrc.common.utils.MsgID;

public class CompanyPositionTask extends AsyncTask<Object, Integer, Void> {
	private String url;
	private Handler mHandler;
	private UserInfo userInfo;
	private List<JobInfo> jobList;
	private JobInfo jobInfo;
	private Company company;

	@Override
	protected Void doInBackground(Object... params) {
		if (params.length < 4) {
			return null;
		}
		mHandler = (Handler) params[0];
		url = (String) params[1];
		userInfo = (UserInfo) params[2];
		jobList = (List<JobInfo>) params[3];
		JSONObject jsonObject = Helpers.getJSONArrayByGet(url);
		Message msg = mHandler.obtainMessage();
		try {
			if (jsonObject == null) {
				msg.what = MsgID.COMPANY_POSITION_QUERY_ERROR;
			} else if (jsonObject.toString().contains("error_code")) {
				// 返回错误
				userInfo.setError_code(jsonObject.getString("error_code"));
				userInfo.setError_message(jsonObject.getString("error_message"));
				msg.what = MsgID.COMPANY_POSITION_QUERY_FAIL;
			} else {
				msg.what = MsgID.COMPANY_POSITION_QUERY_SUCCESS;
				// int total = Integer.parseInt(jsonObject.getString("total"));
				JSONArray jobArray = jsonObject.getJSONArray("jobs");
				for (int i = 0; i < jobArray.length(); i++) {
					jobInfo = new JobInfo();
					company = new Company();
					jobInfo.setModified_at(((JSONObject) jobArray.opt(i)).getString("modified_at"));
					// 下面都一样
					jobInfo.setJob_id(((JSONObject) jobArray.opt(i)).getString("job_id"));
					jobInfo.setTitle(((JSONObject) jobArray.opt(i)).getString("title"));
					jobInfo.setArea(((JSONObject) jobArray.opt(i)).getString("area"));
					JSONObject companyObject = ((JSONObject) jobArray.opt(i)).getJSONObject("company");
					company.setAddress(companyObject.getString("address"));
					company.setCompany_id(companyObject.getString("company_id"));
					company.setLogo_url(companyObject.getString("logo_url"));
					company.setName(companyObject.getString("name"));
					jobInfo.setCompany(company);
					jobList.add(jobInfo);
					company = null;
					jobInfo = null;
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHandler.sendMessage(msg);
		return null;
	}
}